package com.cc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author 33314
 * @version 1.0
 * @description: TODO
 * @date 2025/6/24 14:50
 */
@Configuration
@ComponentScan("com.cc.controller")
@EnableWebMvc
public class SpringMVCConfig implements WebMvcConfigurer {
    /**
     * @description: TODO 配置消息转换器 处理 HTTP 请求和响应的数据转换。比如将 Java 对象转换为 JSON 字符串
     * @author
     * @date
     * @version 1.0
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter converter = new StringHttpMessageConverter();
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converters.add(0, converter);
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 允许所有路径
                .allowedOrigins("http://127.0.0.1:5500")  // 必须与前端完全一致
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")  // 必须包含OPTIONS
                .allowedHeaders("*")  // 允许所有请求头
                .allowCredentials(true)  // 如果前端需要发送凭据（如Cookie）
                .maxAge(3600);  // 预检请求缓存时间
    }

    //配置文件上传解析器
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        // 最大文件 2MB
        commonsMultipartResolver.setMaxUploadSize(1024 * 1024 * 2);

        commonsMultipartResolver.setDefaultEncoding("UTF-8");

        return commonsMultipartResolver;
    }

    // 配置静态资源映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射 classpath 下的 static 目录  classpath:/static/ 是指 src/main/resources/static/
        //映射的是 webapp/static/ 目录，应使用 file:./static/（相对于当前 Web 应用根目录）
//        registry.addResourceHandler("/static/**").addResourceLocations("file:./static/*");

        // 映射用户上传文件的访问路径
        registry.addResourceHandler("/upload/**").
                addResourceLocations("file:./static/upload/");
    }
}
